<?php

namespace app\model;

use think\Model;
use app\model\Staff;
use app\model\User;
use app\model\WaitPayment;

class Enter extends Model
{
    protected $autoWriteTimestamp = true;

    /**
     * 申请入驻
     *
     * @param [type] $enter_data
     * @return void
     */
    public static function createEnter($enter_data)
    {
        $enter = self::where('user_id', $enter_data['user_id'])->find();
        try {
            $enter_data['census_address'] = json_encode($enter_data['census_address']);
            $enter_data['type'] = $enter_data['shenfen'];
            if (!empty($enter) && $enter['type'] > 0) {
                $enter_data['cause'] = '';
                $enter_data['update_time'] = date('Y-m-d H:i:s', time());
                self::where('id', $enter['id'])->update($enter_data);
            } else {
                self::create((array)$enter_data);
            }
        } catch (\Exception $e) {
            error($e->getMessage());
        }

        return true;
    }

    /**
     * 获取所属上级id
     *
     * @param [type] $shenfen
     * @return void
     */
    public static function getBossId($shenfen, $enter_address)
    {
        $shenfen = $shenfen - 1;

        if ($shenfen == 1) {
            if (!empty($enter_address['enter_sheng']) && !empty($enter_address['enter_shi'])) {
                $where = [
                    ['e.shenfen', '=', $shenfen],
                    ['e.enter_sheng', '=', $enter_address['enter_sheng']],
                    ['e.enter_shi', '=', $enter_address['enter_shi']],
                    ['e.type', '=', 0],
                    ['u.status', '=', 0],
                    ['u.delete_time', '=', null],
                ]; 
            } else {
                error('缺少区域参数');
            }
        } elseif ($shenfen == 2) {
            if (!empty($enter_address['enter_sheng']) && !empty($enter_address['enter_shi']) && !empty($enter_address['enter_xian'])) {
                $where = [
                    ['e.shenfen', '=', $shenfen],
                    ['e.enter_sheng', '=', $enter_address['enter_sheng']],
                    ['e.enter_shi', '=', $enter_address['enter_shi']],
                    ['e.enter_xian', '=', $enter_address['enter_xian']],
                    ['e.type', '=', 0],
                    ['u.status', '=', 0],
                    ['u.delete_time', '=', null],
                ];
            } else {
                error('缺少区域参数');
            }
        }
        $list = self::alias('e')
            ->join('user u', 'e.user_id = u.id')
            ->field('u.id, e.name, e.shenfen')
            ->where($where)
            ->select();
        
        if (!empty($list)) {
            return $list;
        } else {
            return [];
        }
    }

    /**
     * 代办事项
     *
     * @param [type] $user_id
     * @param [type] $type
     * @return void
     */
    public static function toDo($user_id)
    {
        $page = input('page');
        if (empty($page)) {
            $page = 1;
        }
        $limit = input('limit');
        if (empty($limit)) {
            $limit = 10;
        }
        $page_count = ($page - 1) * $limit;

        $user_info = self::where('user_id', $user_id)->find();
        if ($user_info['shenfen'] == 3) {
            return ['data' => [], 'count' => 0, 'page' => 1];
        }
        $where = [];
        if ($user_info['shenfen'] == 1) {
            $where[] = ['enter_sheng', '=', $user_info['enter_sheng']]; 
            $where[] = ['enter_shi', '=', $user_info['enter_shi']]; 
            $where[] = ['type', '=', 2]; 
        }
        if ($user_info['shenfen'] == 2) {
            $where[] = ['enter_sheng', '=', $user_info['enter_sheng']]; 
            $where[] = ['enter_shi', '=', $user_info['enter_shi']]; 
            $where[] = ['enter_xian', '=', $user_info['enter_xian']]; 
            $where[] = ['type', '=', 3]; 
        }
        $list['data'] = self::where($where)
            ->field('id, shenfen, name, enter_sheng, enter_shi, enter_xian, enter_xiang, enter_address_details, type')
            ->limit($page_count, $limit)
            ->select();
        $list['count'] = self::where($where)
            ->count();
        $list['page'] = $page;
        return $list;
    }

    /**
     * 通过、驳回入驻申请
     *
     * @param [type] $user_id
     * @param [type] $data
     * @return void
     */
    public static function setType($user_id, $data)
    {
        $enter_type = self::where('id', $data['id'])->value('type');
        if (empty($enter_type)) {
            error('没有此申请申请');
        }
        if ($data['type'] == 4 && empty($data['cause'])) {
            error('驳回原因不能为空');
        }

        $user_info = self::where('user_id', $user_id)->find();
        if ($user_info['shenfen'] - $enter_type != 1) {
            error('不能跨级审核此人');
        }

        try {
            self::where('id', $data['id'])->update(['type' => $user_info['shenfen'], 'cause' => $data['cause'], 'shenhe_time' => date('Y-m-d H:i:s')]);
        } catch (\Exception $e) {
            error($e->getMessage());
        }

        if($data['type'] == 4) {
            return '已驳回';
        } else {
            return '已通过';
        }
    }

    /**
     * 驿站列表
     *
     * @return void
     */
    public static function getList()
    {
        $where[] = ['type', '=', 0];
        // 昵称搜索
        $name = input('name');
        if (!empty($name)) {
            $where[] = ['name', 'like', "%{$name}%"]; 
        }
        // 申请区域搜索
        $enter_sheng = input('enter_sheng');
        if (!empty($enter_sheng)) {
            $where[] = ['enter_sheng', '=', $enter_sheng]; 
        }
        $enter_shi = input('enter_shi');
        if (!empty($enter_shi)) {
            $where[] = ['enter_shi', '=', $enter_shi]; 
        }
        $enter_xian = input('enter_xian');
        if (!empty($enter_xian)) {
            $where[] = ['enter_xian', '=', $enter_xian]; 
        }

        $page = input('page');
        if (empty($page)) {
            $page = 1;
        }
        $limit = input('limit');
        if (empty($limit)) {
            $limit = 10;
        }
        $page_count = ($page - 1) * $limit;

        $list['data'] = self::field('id, user_id, num, name, shenfen, create_time')
            ->where($where)
            ->limit($page_count, $limit)
            ->select()
            ->toArray();
        $list['all_post_houser_count'] = self::where('type', 0)->count();
        $list['all_staff_count'] = Staff::count();
        foreach ($list['data'] as $k => $v) {
            $list['data'][$k]['staff_count'] = Staff::where('boss_id', $v['user_id'])->count();
            $list['data'][$k]['status'] = User::where('id', $v['user_id'])->value('status');
            $list['data'][$k]['wait_payment_money'] = WaitPayment::where('enter_num', $v['num'])->sum('money') ?? 0;
        }
        $list['count'] = self::where($where)->count();
        $list['page'] = $page;
        return $list;
    }

    /**
     * 导入待结算金额
     *
     * @param [type] $data
     * @return void
     */
    public static function importMoney($data)
    {
        // 启动事务
        self::startTrans();
        try {
            $i = 0;
            foreach ($data as $k => $v) {
                $i++;
                $is_exist = WaitPayment::where('enter_num', $v['A'])->where('time', strtotime($v['B']))->find();
                if (!empty($is_exist)) {
                    WaitPayment::where('id', $is_exist['id'])
                        ->update(['enter_num' => $v['A'], 'time' => strtotime($v['B']), 'money' => $v['C'], 'update_time' => date('Y-m-d H:i:s', time())]);
                } else {
                    WaitPayment::create(['enter_num' => $v['A'], 'time' => strtotime($v['B']), 'money' => $v['C']]);
                }
            }
            // 提交事务
            self::commit();
            return $i;
        } catch (\Exception $e) {
            // 回滚事务
            self::rollback();
            // error($e->getMessage());
            error('第'.$i.'条数据错误');
        }
    }

    /**
     * 获取合伙人信息
     *
     * @param [type] $id
     * @return void
     */
    public static function getInfo($id)
    {
        $info = self::field('id, num, shenfen, name, phone, enter_sheng, enter_shi, enter_xian, enter_xiang, enter_address_details, boss_id')->where('id', $id)->find();
        if (!empty($info['boss_id'])) {
            $boss_info = self::where('user_id', $info['boss_id'])->find();
            $info['boss_shenfen'] = $boss_info['shenfen'];
            $info['boss_name'] = $boss_info['name'];
        } else {
            $info['boss_shenfen'] = '';
            $info['boss_name'] = '管理员';
        }
        $info['wait_payment_money'] = WaitPayment::where('enter_num', $info['num'])->sum('money') ?? 0;
        $info['yizhan'] = self::yizhan($info['enter_sheng']);

        return $info;
    }

    /**
     * 获取驿站
     *
     * @param [type] $sheng
     * @return void
     */
    public static function yizhan($sheng)
    {
        $shi = array_unique(self::where('enter_sheng', $sheng)->where('type', 0)->column('enter_shi'));
        foreach($shi as $k => $v) {   
            $xian = array_unique(self::where('enter_shi', $v)->where('type', 0)->column('enter_xian')) ?? [];
            $list[] = ['name' => $v, 'child' => $xian];
        }

        foreach ($list as $k => $v) {
            if (!empty($v['child'])) {
                foreach ($v['child'] as $kk => $vv) {
                    $xiang = array_unique(self::where('enter_sheng', $sheng)->where('enter_shi', $v['name'])->where('enter_xian', $vv)->where('type', 0)->column('enter_xiang')) ?? [];
                    $list[$k]['child'][$kk] = ['name' => $vv, 'child' => $xiang];
                }
            }
        }

        return $list;
    }
}
